const {getRoleList, updateRole} = require("../controller/role");
const {SuccessModel, ErrorModel} = require('../model/response')
var express = require('express');
const {getAuthorityList} = require("../controller/authority");
var router = express.Router();

/**
 * 管理员路由操作
 * Login.vue: /list/only
 * Role.vue: /list, /update,
 */
// 获取角色与权限列表
router.get('/list', async (req, res, next) => {
  const roles = await getRoleList()
  let rights = await getAuthorityList()
  // 过滤角色已有的权限
  roles.forEach(item => {
    item.children = rights.filter(ele => ele.role_id === item.id && ele.level === 0 && ele.isown === 0);
    item.children.forEach(sub => {
      sub.children = rights.filter(thr => thr.pid === sub.id && thr.level === 1 && thr.isown === 0);
    })
  })
  res.json(new SuccessModel(roles))
})
// 仅获取角色信息
router.get('/list/only', (req, res, next) => {
  const result = getRoleList()
  return result.then(rows => {
    res.json(new SuccessModel(rows))
  })
})
// 修改角色描述信息
router.post('/update', (req, res, next) => {
  const result = updateRole(req.body)
  return result.then(val => {
    if (val) {
      res.json(new SuccessModel(`修改${req.body.role_name}角色描述成功`))
    } else {
      res.json(new ErrorModel(`修改${req.body.role_name}角色描述失败`))
    }
  })
})

module.exports = router
